<template>
  <div class="teaching-mission-browse">
    <div class="page-header">
      <h1>浏览教学任务</h1>
      <div class="actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索过滤组件 -->
    <TeachingMissionSearchFilter
      :search-form="searchForm"
      :terms="terms"
      :courses="courses"
      @update:term-id="searchForm.termId = $event"
      @update:course-id="searchForm.courseId = $event"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 教学任务表格组件 -->
    <FrontendTeachingMissionTable
      :table-data="tableData"
      :loading="loading"
      :pagination="pagination"
      @selection-change="handleSelectionChange"
      @manage-scores="handleManageScores"
      @write-summary="handleWriteSummary"
      @modify-summary="handleModifySummary"
      @view-summary="handleViewSummary"
      @dropdown-command="handleDropdownCommand"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @manage-teachers="handleManageTeachers"
      @assign-teachers="handleAssignTeachers"
    />

    <!-- 总结详情对话框 -->
    <SummaryViewDialog
      v-model:visible="summaryDialogVisible"
      :summaryId="currentSummaryId"
      @close="handleDialogClose"
    />

    <!-- 教师排序对话框 -->
    <TeacherSortingDialog
      v-model:visible="teacherSortingVisible"
      :mission-id="currentMissionId"
      :mission-data="currentMissionData"
      :teachers="currentTeachers"
      @success="handleTeacherSortingSuccess"
      @close="handleTeacherSortingClose"
    />

  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';
import { 
  getMyTeachingMissions
} from '@/api/teaching-mission';
import { 
  courseApi,
  termApi
} from '@/api/base-data';
import { convertToBackendPagination } from '@/utils/pagination';
import TeachingMissionSearchFilter from '@/components/teaching-mission/filters/TeachingMissionSearchFilter.vue';
import FrontendTeachingMissionTable from '@/components/teaching-mission/tables/FrontendTeachingMissionTable.vue';
import SummaryViewDialog from '@/components/common/SummaryViewDialog.vue';
import TeacherSortingDialog from '@/components/teaching-mission/TeacherSortingDialog.vue';

export default {
  name: 'TeachingMissionBrowse',
  components: {
    Refresh,
    TeachingMissionSearchFilter,
    FrontendTeachingMissionTable,
    SummaryViewDialog,
    TeacherSortingDialog
  },
  setup() {
    const router = useRouter();
    
    // 状态管理
    const loading = ref(false);
    
    // 搜索表单
    const searchForm = ref({
      termId: '',
      courseId: ''
    });
    
    // 表格数据
    const tableData = ref([]);
    const selectedRows = ref([]);
    
    // 分页
    const pagination = ref({
      current: 1,
      pageSize: 20,
      total: 0
    });
    
    // 基础数据
    const courses = ref([]);
    const terms = ref([]);

    // 对话框状态管理
    const summaryDialogVisible = ref(false);
    const currentSummaryId = ref(null);
    
    // 教师排序对话框状态
    const teacherSortingVisible = ref(false);
    const currentMissionId = ref(null);
    const currentMissionData = ref({});
    const currentTeachers = ref([]);

    // 获取当前学期并设置为默认值
    const getCurrentTerm = (terms) => {
      // 查找标记为当前学期的记录
      const currentTerm = terms.find(term => term.isCurrent === true || term.is_current === true);
      
      // 如果没有找到当前学期，返回null（不设置默认值）
      if (!currentTerm && terms.length > 0) {
        console.warn('未找到标记为当前学期的数据，请在后台设置当前学期');
      }
      
      return currentTerm || null;
    };

    // 修改获取基础数据方法
    const fetchBaseData = async () => {
      try {
        const [termsData] = await Promise.all([
          termApi.getAllTerms()
        ]);
        
        terms.value = termsData || [];
        
        // 设置当前学期为默认值
        const currentTerm = getCurrentTerm(terms.value);
        if (currentTerm) {
          searchForm.value.termId = currentTerm.id;
          // 获取当前学期下用户的教学任务课程
          await fetchCoursesForTerm(currentTerm.id);
        }
      } catch (error) {
        console.error('获取基础数据失败:', error);
        ElMessage.error('获取基础数据失败');
      }
    };
    
    // 获取指定学期下用户的教学任务课程
    const fetchCoursesForTerm = async (termId) => {
      if (!termId) {
        courses.value = [];
        return;
      }
      
      try {
        // 先获取用户在该学期的教学任务
        const params = { termId, size: 1000 }; // 获取所有记录用于课程筛选
        const result = await getMyTeachingMissions(params);
        
        if (result && result.content) {
          // 从教学任务中提取课程信息
          const courseMap = new Map();
          result.content.forEach(mission => {
            if (mission.courseId && mission.courseName) {
              courseMap.set(mission.courseId, {
                id: mission.courseId,
                name: mission.courseName,
                code: mission.courseCode
              });
            }
          });
          courses.value = Array.from(courseMap.values());
        } else {
          courses.value = [];
        }
      } catch (error) {
        console.error('获取课程列表失败:', error);
        courses.value = [];
      }
    };
    
    // 监听学期变化，更新课程列表
    watch(() => searchForm.value.termId, async (newTermId) => {
      await fetchCoursesForTerm(newTermId);
      // 清空课程选择
      searchForm.value.courseId = null;
      // 自动触发搜索以更新教学任务列表
      pagination.value.current = 1;
      await fetchMyTeachingMissions();
    });
    
    // 监听课程变化，自动触发搜索
    watch(() => searchForm.value.courseId, async () => {
      pagination.value.current = 1;
      await fetchMyTeachingMissions();
    });
    
    // 转换后端数据格式为前端期望格式
    const transformMissionData = (missions) => {
      return missions.map(mission => ({
        ...mission,
        course: {
          id: mission.courseId,
          name: mission.courseName,
          code: mission.courseCode
        },
        term: {
          id: mission.termId,
          name: mission.termName
        },
        major: {
          ids: mission.majorIds,
          name: mission.majorNames ? mission.majorNames.join(', ') : ''
        },
        cengCi: {
          ids: mission.cengCiIds,
          name: mission.cengCiNames ? mission.cengCiNames.join(', ') : ''
        },
        teachers: mission.teacherNames ? mission.teacherNames.map((name, index) => ({
          id: mission.teacherIds ? mission.teacherIds[index] : null,
          name: name,
          sortOrder: mission.teacherOrders ? mission.teacherOrders[index] : (index + 1),
          isPrimary: mission.teacherPrimaryFlags ? mission.teacherPrimaryFlags[index] : false
        })) : [],
        classes: mission.classNames ? mission.classNames.map((name, index) => ({
          id: mission.classIds ? mission.classIds[index] : null,
          name: name
        })) : []
      }));
    };

    // 获取我的教学任务
    const fetchMyTeachingMissions = async () => {
      loading.value = true;
      try {
        // 使用统一的分页参数转换工具
        const backendParams = convertToBackendPagination(pagination.value);
        const params = {
          ...backendParams,
          ...searchForm.value
        };
        
        const result = await getMyTeachingMissions(params);
        
        if (result) {
          tableData.value = transformMissionData(result.content || []);
          pagination.value.total = result.totalElements || 0;
        }
      } catch (error) {
        console.error('获取教学任务失败:', error);
        ElMessage.error('获取教学任务失败');
      } finally {
        loading.value = false;
      }
    };

    // 成绩管理
    const handleManageScores = (mission) => {
      router.push({
        path: '/teaching-mission/score',
        query: { missionId: mission.id }
      });
    };

    // 填写课程教学总结
    const handleWriteSummary = (mission) => {
      router.push({
        path: '/kcjxzj/summary-edit/new',
        query: { 
          missionId: mission.id,
          courseId: mission.course?.id,
          termId: mission.term?.id
        }
      });
    };

    // 修改课程教学总结
    const handleModifySummary = (mission) => {
      if (mission.kcjxzjId) {
        router.push({
          path: `/kcjxzj/summary-edit/${mission.kcjxzjId}`,
          query: { 
            missionId: mission.id
          }
        });
      } else {
        ElMessage.warning('该教学任务尚未关联课程教学总结');
      }
    };

    // 处理下拉菜单命令（已移除所有下拉菜单功能）
    const handleDropdownCommand = async (command, mission) => {
      // 所有功能已整合到主按钮中，此方法保留以防未来扩展
      console.warn('未知的下拉菜单命令:', command);
    };

    // 查看总结
    const handleViewSummary = async (mission) => {
      if (mission.kcjxzjId) {
        // 使用对话框显示总结详情，而不是路由跳转
        currentSummaryId.value = mission.kcjxzjId;
        summaryDialogVisible.value = true;
      } else {
        ElMessage.warning('该教学任务尚未关联课程教学总结');
      }
    };

    // 搜索事件处理
    const handleSearch = () => {
      pagination.value.current = 1;
      fetchMyTeachingMissions();
    };

    // 重置事件处理
    const handleReset = () => {
      searchForm.value = {
        termId: '',
        courseId: ''
      };
      courses.value = [];
      pagination.value.current = 1;
      fetchMyTeachingMissions();
    };

    // 刷新数据
    const refreshData = () => {
      fetchMyTeachingMissions();
    };

    // 选择改变
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection;
    };

    // 教师管理相关处理函数
    const handleManageTeachers = (mission) => {
      currentMissionId.value = mission.id;
      currentMissionData.value = {
        courseName: mission.course?.name || mission.courseName,
        termName: mission.term?.name || mission.termName,
        majorName: mission.major?.name || mission.majorNames?.join(', '),
        cengCiName: mission.cengCi?.name || mission.cengCiNames?.join(', ')
      };
      currentTeachers.value = mission.teachers || [];
      teacherSortingVisible.value = true;
    };

    const handleAssignTeachers = (mission) => {
      // 如果没有教师，直接打开教师排序对话框
      handleManageTeachers(mission);
    };

    const handleTeacherSortingSuccess = async (result) => {
      ElMessage.success('教师排序更新成功');
      // 刷新教学任务数据
      await fetchMyTeachingMissions();
    };

    const handleTeacherSortingClose = () => {
      currentMissionId.value = null;
      currentMissionData.value = {};
      currentTeachers.value = [];
    };

    // 分页大小改变
    const handleSizeChange = (size) => {
      pagination.value.pageSize = size;
      pagination.value.current = 1;
      fetchMyTeachingMissions();
    };

    // 当前页改变
    const handleCurrentChange = (page) => {
      pagination.value.current = page;
      fetchMyTeachingMissions();
    };

    // 对话框关闭处理
    const handleDialogClose = () => {
      currentSummaryId.value = null;
      summaryDialogVisible.value = false;
    };

    // 页面初始化
    onMounted(async () => {
      await fetchBaseData();
      await fetchMyTeachingMissions();
    });

    return {
      loading,
      searchForm,
      tableData,
      selectedRows,
      pagination,
      courses,
      terms,
      summaryDialogVisible,
      currentSummaryId,
      handleSearch,
      handleReset,
      refreshData,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleManageScores,
      handleWriteSummary,
      handleModifySummary,
      handleViewSummary,
      handleDropdownCommand,
      handleDialogClose,
      handleManageTeachers,
      handleAssignTeachers,
      handleTeacherSortingSuccess,
      handleTeacherSortingClose,
      // 对话框状态
      teacherSortingVisible,
      currentMissionId,
      currentMissionData,
      currentTeachers
    };
  }
};
</script>

<style scoped>
.teaching-mission-browse {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.actions {
  display: flex;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
